import { ForbiddenException, Injectable, Post } from '@nestjs/common';
import { CategoryRepository, CommentRepository, PostRepository } from 'src/entity/repositories';
import { isNil } from 'lodash';
import { CommentEntity, PostEntity } from 'src/entity/Entity';
import { SelectQueryBuilder, EntityNotFoundError } from 'typeorm';
import { CreateCommentDto, QueryCommentDto } from 'src/Dto/Comment.Dto';
import { manualPaginate, paginate } from 'src/database/helpers';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class CommentService {
    constructor(
        protected commentRepository: CommentRepository,
        @InjectRepository(PostEntity)
        protected postRepository: PostRepository,
        protected categoryRepository: CategoryRepository

    ) { }


    async findTree() {
        const options = {
            post: 'c525af82-955d-4d40-b869-7d1d519f3722'

        };
        return this.commentRepository.findTree({
            addQuery: (qb) => {
                return isNil(options.post) ?
                    qb : qb.where('comment.id = :id', { id: options.post });
            },
        });
    }
    //查找一篇文章的评论并分页

    async FindCommentAndPaging(dto: QueryCommentDto) {

        let { post, ...query } = dto

        let addQuery = (qb: SelectQueryBuilder<CommentEntity>) => {
            const condition: { [key: string]: any } = {}
            if (!isNil(post)) { condition.post = post }
            return Object.keys(condition).length > 0 ? qb.andWhere(condition) : qb

        }



        let data = await this.commentRepository.findRoots({ addQuery })

        let comment: CommentEntity[] = []

        for (let i = 0; i < data.length; i++) {
            const c = data[i]
            comment.push(
                await this.commentRepository.findDescendantsTree(c, { addQuery })
            )
        }

        //查出的数据进行打平
        let comments = await this.commentRepository.toFlatTrees(comment)
        //对数据进行整理
        return manualPaginate(query, comments)

    }

    /**
     * 获取请求传入的父分类
     * @param current 当前分类的ID
     * @param id   
     */
    //获取请求传入的父分类
    protected async getParent(current?: string, id?: string) {
        if (current == id) return undefined
        let parent: CommentEntity | undefined
        if (id != undefined) {
            if (id == null) return null
            parent = await this.commentRepository.findOne({
                relations: ['parent', 'post'],
                where: { id }
            })

            if (!parent) {
                throw new EntityNotFoundError(CommentEntity, `Parent Comment ${id} Is Not Find`)
            }


        }
        return parent
    }
    /**
        * 新增评论
        * @param data
        * @param user
        */
    protected async getPost(id: string) {
        return !isNil(id) ? this.postRepository.findOneOrFail({ where: { id } }) : id;
    }

    async create(data: CreateCommentDto) {

        const parent = await this.getParent(undefined, data.parent);
        if (!isNil(parent) && parent.post.id !== data.post) {
            throw new ForbiddenException('Parent comment and child comment must belong same post!');
        }
        let item =await this.commentRepository.createQueryBuilder('comment')
            .insert()
            .values({
                ...data,
                parent,
                post: await this.postRepository.findOne({ where: { id: data.post } }),
            })
            .execute()

      //  console.log(item);
      if(item.identifiers[0].id){
        return await this.commentRepository.findOne({where:{id:item.identifiers[0].id}})
      }



    }

  /**
     * 删除评论
     * @param id
     */
  async delete(id: string) {
    const comment = await this.commentRepository.findOneOrFail({ where: { id: id ?? null } });
    return this.commentRepository.remove(comment);
}

}